import { createToken, getTokenInfo, destroyToken } from '@/api/admin/token';
import { getToken, setToken, removeToken, removeUserTrees, getUserTrees } from '@/utils/auth';
import { Notification } from 'element-ui';
// import { getUserTree } from '@/api/common';

import md5 from 'md5';

const user = {
  state: {
    user: '',
    agentId: '',
    status: '',
    code: '',
    userTree: getUserTrees(),
    token: getToken(),
    name: '',
    avatar: '',
    pwdForce: false,
    introduction: '',
    roles: [],
    accessList: [],
    setting: {
      articlePlatform: []
    },
    orgList: []
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code;
    },
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_USERTREE: (state, userTree) => {
      state.userTree = userTree;
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction;
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting;
    },
    SET_STATUS: (state, status) => {
      state.status = status;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_PWDFORCE: (state, pwdForce) => {
      state.pwdForce = pwdForce;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_ACCESS: (state, accessList) => {
      state.accessList = accessList;
    },
    SET_AGENTID: (state, agentId) => {
      state.agentId = agentId;
    },
    SET_ORGLIST: (state, orgList) => {
      state.orgList = orgList;
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit }, params) {
      if (params.loginType === 0) {
        params.agentAuth = md5(params.agentAuth);
      }
      return new Promise((resolve, reject) => {
        createToken(params).then(response => {
          const result = response.data;
          if (result.code === 0) {
            commit('SET_TOKEN', result.data.token);
            setToken(result.data.token);
            // getUserTree().then(res => {
            //   if (res.data.code === 0) {
            //     const userId = res.data.data.id;
            //     commit('SET_USERTREE', userId);
            //     setUserTrees(userId);
            //   }
            // });
            if (!result.data.userInfo.pwdForce) {
              if (result.data.userInfo.pwdTips) {
                Notification.success({
                  title: '修改提醒',
                  message: '密码长期未修改，请进行修改！'
                });
              }
            }
            resolve();
          } else {
            reject(result);
          }
        }).catch(error => {
          reject(error);
        });
      });
    },
    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getTokenInfo().then(response => {
          // 由于mockjs 不支持自定义状态码只能这样hack
          if (!response.data) {
            reject('Verification failed, please login again.');
          }
          const result = response.data;
          const roles = result.data.userInfo.roles;
          const accessList = result.data.userInfo.accessList;

          if (roles && roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', roles);
          } else {
            reject('getInfo: roles must be a non-null array!');
          }
          if (accessList && accessList.length > 0) {
            commit('SET_ACCESS', accessList);
          }
          // commit('SET_PWDFORCE', result.data.userInfo.pwdForce);
          console.log(result.data.userInfo.name);
          commit('SET_NAME', result.data.userInfo.name);
          commit('SET_AVATAR', result.data.userInfo.avatar);
          commit('SET_AGENTID', result.data.userInfo.agentId);
          commit('SET_ORGLIST', result.data.userInfo.orgList);
          // commit('SET_INTRODUCTION', data.introduction);
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        destroyToken().then(() => {
          commit('SET_TOKEN', '');
          commit('SET_ROLES', []);
          commit('SET_ACCESS', []);
          removeToken();
          removeUserTrees();
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        removeToken();
        removeUserTrees();
        resolve();
      });
    },

    // 动态修改权限
    ChangeRoles({ commit, dispatch }, role) {
      return new Promise(resolve => {
        // commit('SET_TOKEN', role);
        // setToken(role);
        getTokenInfo().then(response => {
          const result = response.data;
          commit('SET_ROLES', result.data.userInfo.roles);
          commit('SET_ACCESS', result.data.userInfo.accessList);
          commit('SET_NAME', result.data.userInfo.name);
          commit('SET_AVATAR', result.data.userInfo.avatar);
          // commit('SET_INTRODUCTION', data.introduction);
          dispatch('GenerateRoutes', result.data.userInfo.accessList); // 动态修改权限后 重绘侧边菜单
          resolve();
        });
      });
    }
  }
};

export default user;
